#!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#      http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Root page."""

import datetime
import logging
import os
import imghdr
import re
import urllib
from StringIO import StringIO
from google.appengine.ext import db
from google.appengine.api import datastore_types
from google.appengine.api import datastore_errors
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import wsgiref.handlers

#error map
errormsgs = {}
errormsgs["siteunknown"] = "You have requested a site which does not exist"
errormsgs["unknownsite"] = "You have requested a site which does not exist"
errormsgs["noauth"] = "You must be authenticated for this operation"
errormsgs["badauth"] = "You are not authorized for this operation"
errormsgs["notsiteowner"] = "You are not authorized for this operation"
errormsgs["pathexists"] = "A site with this path already exists. Please change the path or edit the existing site."
errormsgs["pathrequired"] = "You must supply a path for your site"
errormsgs["logotoobig"] = "You logo image exceeded 200kb"
errormsgs["logorequired"] = "You must supply a logo for your site"
errormsgs["gettokenfailed"] = "Unable to retrieve an upload token for YouTube"



class Site(db.Model):
  
  """model for a subsite."""  
  owner = db.UserProperty()
  display_name = db.StringProperty()
  description = db.TextProperty()
  path = db.StringProperty()
  base_query = db.StringProperty()
  color = db.StringProperty()
  logo = db.BlobProperty()
  logotype = db.StringProperty()
  usercount = db.IntegerProperty()
  videocount = db.IntegerProperty()
  featured_video = db.StringProperty()
  counts_update_stamp = db.DateTimeProperty()
  
class Video(db.Model):
  
  """model for videos uploaded at this site."""
  
  user = db.UserProperty()
  id = db.StringProperty()
  status = db.StringProperty()
  reason = db.StringProperty()
  site = db.Reference(Site)

  
class CachedVideo(db.Model):
  
  """model for videos retrieved via live youtube feed."""
  
  id = db.StringProperty()
  title = db.StringProperty()
  desc = db.TextProperty()
  keywords = db.StringProperty()
  from_site = db.BooleanProperty()
  site = db.Reference(Site)
  date = db.DateTimeProperty(auto_now_add=True)


class TubeUser(db.Model):
  
  """model for users of this site."""
    
  user = db.UserProperty()
  featured_video = db.StringProperty()
  nickname = db.StringProperty()
  auth_token = db.StringProperty()
  site = db.Reference(Site)


def if_else(condition, t_val, f_val):
  
  """convenience method emulating ternary operator."""
  
  if condition:
    return t_val
  else:
    return f_val

  
def GetSite(sitepath):
  results = Site.gql("WHERE path = :1",sitepath)
  for site in results:
    return site
  return None


def PrintHeader(request, response):
  
  """render the header html for the site browse/creation interface."""
  
  #TODO - check for error messages, find string value, add to template values
  user = users.GetCurrentUser()
  username = ""
  loggedin = user is not None
  if loggedin:
    username = user.nickname()
  
  errormsg = None
  if request.get('error') and request.get('error') != '':
    errormsg = errormsgs[request.get('error')]
    if not errormsg:
      errormsg = 'Unknown'
    logging.error('error - '+errormsg)
  
  template_values = {'logouturl': users.CreateLogoutURL(request.uri),
                     'loginurl': users.CreateLoginURL(request.uri),
                     'username': username,
                     'loggedin': loggedin,
                     'errormsg': errormsg
                     }

  path = os.path.join(os.path.dirname(__file__), 'base_header.html')
  response.out.write(template.render(path, template_values))

   
class MainPage(webapp.RequestHandler):
  
  """render the landing page for the site."""
  
  def get(self):
    
    """get request."""
    
    user = users.GetCurrentUser()
    sites = Site.gql("ORDER BY usercount DESC LIMIT 1000")
    site = None
    editmode = False
    usersites = Site.gql("WHERE owner = :1",user)
    
    editsitepath = self.request.get("edit")
    if editsitepath is None or editsitepath == "":
      # construct a new template site
      site = Site()
      site.display_name = "my awesome site"
      site.color = "#AABBCC"
      site.base_query = "robots"
      if user:
        site.path = user.email().split("@")[0]+"site1"
    else:
      #retrieve existing site
      matches = Site.gql("WHERE owner = :1 and path = :2", user, editsitepath)
      site = None
      for tmp in matches:
        site = tmp
        editmode = True
        break
      if not site:
        logging.error('bad sitepath - '+str(editsitepath))
        self.redirect('/?error=unknownsite')
        return           
    
    sites_w_counts = []
    for countsite in sites:
      #get timestamp for current site
      oldtime = countsite.counts_update_stamp
      
      #if none or stale (>60 minutes) - calculate
      if (not oldtime) or (datetime.datetime.now() - oldtime).seconds > 1200:
        countsite.usercount = int(TubeUser.gql("WHERE site = :1",countsite.key()).count())
        countsite.videocount = int(Video.gql("WHERE site = :1",countsite.key()).count())
        countsite.counts_update_stamp = datetime.datetime.now()
        #if calculated just now, update object in db
        countsite.put()            
        logging.info('updating cached site counts')
      
      sites_w_counts.append(countsite)
    
    page = self.request.get('page')
    page = if_else((page is None) or (page == ""), '1', page)
    offset =(10*(int(page)-1))
    sites_w_counts = sites_w_counts[offset:offset+10]
    
    PrintHeader(self.request, self.response)
    template_values = {'user': user,
                       'usersites': usersites,
                       'sites': sites_w_counts,
                       'edit': editmode,
                       'site': site,
                       'previousurl': if_else(int(page) > 1,
                                              "?page=" +
                                              str(int(page) - 1), None),
                       'nexturl': "?page="+str(int(page) + 1)
                       }
            
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))
    

  def post(self):
    
    """add or update a site."""
    
    user = users.GetCurrentUser()
    if not user:
      self.redirect('/?error=noauth')
      return
      
    newsite = Site()
    logging.info('encoded - '+urllib.quote(self.request.get('path')))
    # check action to see if this is an edit.
    if self.request.get("edit") and self.request.get("edit") != "":
      newsite = db.get(self.request.get("edit"))
      if not newsite:
        self.redirect('/?error=unknownsite')
        return
      if newsite.owner != user:
        self.redirect('/?error=badauth')
        return
      if self.request.get('logo') != "":
        newsite.logo = self.request.get('logo')  
    else:
      #check for duplicate path
      dupe = int(Site.gql("WHERE path = :1",self.request.get('path')).count())
      if dupe > 0:
        self.redirect('/?error=pathexists')
        return     
      try:
        if len(self.request.get('logo')) > 200000:  # block images larger than 200k
          self.redirect('/?error=logotoobig')
          return
        if not self.request.get('logo') or self.request.get('logo') == '':
          self.redirect('/?error=logorequired')
          return
        newsite.logo = datastore_types.Blob(str(self.request.get('logo')))
      except datastore_errors.BadValueError:
        self.redirect('/?error=logorequired')
        return
      
    
    newsite.owner = user
    newsite.display_name = self.request.get('display_name')
    #display name is escaped later    
    newsite.description = self.request.get('description')
    #description is escaped later    
    newsite.base_query = self.request.get('base_query')
    #base_query is url encoded later, so user can screw it up here
     
    #get rid of non alphanum
    tmppath = re.sub('\W','',self.request.get('path').strip())
    if tmppath == "":
      self.redirect('/?error=pathrequired')
      return 
    newsite.path = tmppath
    
    newsite.color = self.request.get('color')
    #can be any css valid color, escaped later
    
    newsite.logotype = imghdr.what(StringIO(newsite.logo))
    
    newsite.put()
      
    self.redirect('/')
    
    
class ImageServer(webapp.RequestHandler):
  
  """render the landing page for the site."""
  
  def get(self, site):   
    site = GetSite(site)
    if not site:
      logging.error("image not found")
      return
    
    resultimg = site.logo
    
    if isinstance(resultimg, datastore_types.Blob):      
      #self.response.clear()
      #self.response.headers['Content-Type'] = "image/%s\n" % imghdr.what(StringIO(resultimg))
      self.response.headers['Content-Type'] = "image"
      self.response.out.write(resultimg)
 
    else:
      logging.error("image not found")
      self.redirect('/images/grad_white.png')
      return
  

class About(webapp.RequestHandler):
  
  """render the landing page for the site."""
  
  def get(self):   
    PrintHeader(self.request, self.response)
    template_values = {}
            
    path = os.path.join(os.path.dirname(__file__), 'about.html')
    self.response.out.write(template.render(path, template_values))
    
def main():
  application = webapp.WSGIApplication([('/', MainPage),
                                        ('/about', About),                                                                                
                                        (r'/getimg/([^\.]*)\..*', ImageServer)],debug=False)
  logging.getLogger().setLevel(logging.DEBUG)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
